package io.gitee.cloudladder.obsidian.swagger2.plugin;

import com.alibaba.fastjson.JSON;
import io.gitee.cloudladder.obsidian.swagger2.annotation.ApiResponseExample;
import io.gitee.cloudladder.obsidian.swagger2.example.ResponseExampleGenerator;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.Arrays;
import java.util.Objects;

@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public class ApiResponseExampleBuilderPlugin implements OperationBuilderPlugin {

    @Override
    public void apply(OperationContext operationContext) {
        ApiResponseExample apiResponseExample = operationContext.getHandlerMethod().getMethodAnnotation(ApiResponseExample.class);
        if (Objects.nonNull(apiResponseExample)) {
            try {
                ResponseExampleGenerator generator = apiResponseExample.value().newInstance();
                Object obj = generator.generate();
                operationContext.operationBuilder().extensions(Arrays.asList(
                        new StringVendorExtension("x-response-example", JSON.toJSONString(obj, true))
                ));
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

}
